<template>
  <view class="main" :style="{height: (windowHeight - 44) + 'px'}">
    <!--  搜索框-->
    <view class="search">
      <uni-search-bar v-model="state.query.kw" bgColor="#dcdcdc" radius="5" placeholder="搜索" clearButton="auto"
                      cancelButton="none" @confirm="search"
                      @cancel="cancel"/>
    </view>
    <!-- 排序条件 -->
    <view class="sort">
      <view class="item" @tap="clickSort(1)" :class="state.sort.activeTab.idx===1 ? 'item-active' : ''">
        <text>综合</text>
        <uni-icons
            v-if="state.sort.activeTab.idx===1"
            :type="state.sort.activeTab.clickTimes % 2 === 0 ?
            state.sort.icon.type.active.asc: state.sort.icon.type.active.desc"
            :color="state.sort.icon.color.active"
            size="15"></uni-icons>
      </view>
      <view class="item" @tap="clickSort(2)" :class="state.sort.activeTab.idx===2 ? 'item-active' : ''">
        <text>销量</text>
        <uni-icons v-if="state.sort.activeTab.idx===2" :type="state.sort.activeTab.clickTimes % 2 === 0 ?
            state.sort.icon.type.active.asc: state.sort.icon.type.active.desc"
                   :color="state.sort.icon.color.active" size="15" ></uni-icons>
      </view>
      <view class="item" @tap="clickSort(3)" :class="state.sort.activeTab.idx===3 ? 'item-active' : ''">
        <text>价格</text>
        <uni-icons v-if="state.sort.activeTab.idx===3" :type="state.sort.activeTab.clickTimes % 2 === 0 ?
            state.sort.icon.type.active.asc: state.sort.icon.type.active.desc"
                   :color="state.sort.icon.color.active"  size="15"></uni-icons>
      </view>
    </view>
    <scroll-view class="result" :lower-threshold="50" @scrolltolower="loadMore"
                 :style="{height: (windowHeight - 44 - 50 -50) + 'px'}" :scroll-y="true">
      <!-- 商品列表 -->
      <productListCom :product-list="state.list" />
      <uni-load-more :content-text="state.scroll.contentText" :status="state.scroll.loadingStatus"
                     :icon-type="state.scroll.iconType"></uni-load-more>
    </scroll-view>
  </view>
</template>
<script setup lang="ts">
// 获取屏幕边界到安全区域距离
import {searchProductListData} from "@/services/home";
import {onLoad} from "@dcloudio/uni-app";
import {ref} from "vue";
import ProductListCom from '@/components/product/list.vue'
import type {ISort, PageQueryType} from "@/types/global";
import {ProductItemCls} from "@/types/productcls";
import type {ProductSearchType} from "@/types/home";

const {windowHeight} = uni.getWindowInfo()

const state = ref({
  sort: {
    activeTab: { // 排序规则
      idx: 1, // 表示选中的tab，每次切换idx时要重置clickTimes
      clickTimes: 1 // 点击的次数，用于控制升序、倒序, 默认是倒序
    },
    icon: { // 排序规则中标签的指向
      type: {
        default: "",
        active: {
          asc: "up",
          desc: "down"
        }
      },
      color: {
        active: "#dd524d",
        default: "#000",
      },
    }
  },
  scroll: {
    hasMore: true, // 是否还有下一页
    loadingStatus: "more" as "more" | "loading" | "no-more",
    iconType: "auto" as "auto" | "snow" | "circle",
    contentText: {
      contentdown: "上滑加载更多",
      contentrefresh: "正在加载...",
      contentnomore: "没有更多数据了"
    }
  },
  list: [] as Array<ProductItemCls>,
  query: {
    kw: "",
    category: 0,
    page: {
      page: 1,
      size: 10,
      orders: [] as Array<ISort>
    } as PageQueryType
  } as ProductSearchType
})

const cancel = (res: any) => {
  uni.showToast({
    title: '点击取消，输入值为：' + res.value,
    icon: 'none'
  })
}

const search = (res: any) => {
  uni.showToast({
    title: '搜索：' + res.value,
    icon: 'none'
  })
  // 重置搜索条件
  state.value.query.page.page = 1
  state.value.query.page.orders = [{column: "default", asc: false}]
  // 清空之前的数据
  state.value.list = []
  queryProductList()
}
/**
 * 切换排序规则
 * 排序规则映射关系
 * 1=default
 * 2=sold
 * 3=price
 * @param idx
 */
const clickSort = (idx: number) => {
  // 重置分页参数
  state.value.query.page.page = 1
  // 清空列表
  state.value.list = []
  // 重置搜索条件
  const order = {
    column: "",
    asc: false
  }
  switch (idx) {
    case 1:
      order.column = 'default'
          break
    case 2:
      order.column = 'sales'
          break
    case 3:
      order.column = 'price'
          break
    default:
      order.column = 'default'
  }
  if (state.value.sort.activeTab.idx !== idx) {
    state.value.sort.activeTab.idx = idx
    state.value.sort.activeTab.clickTimes = 1

    order.asc = false
  } else {
    state.value.sort.activeTab.clickTimes += 1
    order.asc = true
  }
  state.value.query.page.orders = [order]
  queryProductList()
}
const loadMore = () => {
  state.value.query.page.page += 1
  queryProductList()
}
/**
 * 查询关键词的商品
 */
const queryProductList =async () => {
  state.value.scroll.loadingStatus = "loading"
  await searchProductListData(state.value.query).then((r) => {
    if (r.code === 1000) {
      state.value.scroll.loadingStatus = "no-more"
      return
    }
    if (r.code === 0) {
      state.value.list.push(...r.data.list)
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
    state.value.scroll.loadingStatus = "more"
  }).catch((e) => {
    state.value.scroll.loadingStatus = "no-more"
    console.log("@search product err: ", e)
    uni.showToast({
      title: "网络错误，请稍后再试",
      icon: "none"
    })
  })
  // 如果是第一页，并且数据少于页面能容纳的最大条数时，load的状态设置为没有更多了
  if (state.value.query.page.page === 1 && state.value.list.length <= 6) {
    state.value.scroll.loadingStatus = "no-more"
  }
}

// 接收请求的参数
onLoad((params: any) => {
  console.log("goods params: ", params)
  state.value.query.kw = params.kw
  state.value.query.category = params.category
  queryProductList()
})
</script>
<style lang="scss">
.main {
  .search {
    height: 50px;
  }

  .sort {
    height: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;

    .item {
      width: 50px;
      font-size: 15px;
      font-weight: bold;
    }

    .item-active {
      color: $uni-color-error;
    }
  }

  .result {
    overflow-y: auto;
  }
}
</style>